import matplotlib.pyplot as plt

file_path = 'spi.dat'

# 读取数据
time_points = []
PA5, PA6, PA7 = [], [], []

with open(file_path, 'r') as file:
    current_time = 0.0
    for line in file:
        line = line.strip()
        if "[GPIO]" in line:
            # 解析GPIO状态
            state_str = line.split('[GPIO] ')[1]
            states = state_str.split()
            
            PA5.append(int(states[0].split(':')[1]))
            PA6.append(int(states[1].split(':')[1]))
            PA7.append(int(states[2].split(':')[1]))
            time_points.append(current_time)
            
        elif "[DELAY]" in line:
            # 累加延迟时间（转换为秒）
            current_time += int(line.split()[1].replace('ms', '')) / 1000

# 创建三个垂直排列的子图
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(12, 8), sharex=True)

# 绘制SCK信号（PA5）
ax1.step(time_points, PA5, where='post', color='r', linewidth=1)
ax1.set_ylabel('SCK (PA5)')
ax1.set_yticks([0, 1])
ax1.set_yticklabels(['Low', 'High'])
ax1.grid(True)

# 绘制SS信号（PA6） 
ax2.step(time_points, PA6, where='post', color='g', linewidth=1)
ax2.set_ylabel('SS (PA6)')
ax2.set_yticks([0, 1])
ax2.set_yticklabels(['Low', 'High'])
ax2.grid(True)

# 绘制MOSI信号（PA7）
ax3.step(time_points, PA7, where='post', color='b', linewidth=1)
ax3.set_ylabel('MOSI (PA7)')
ax3.set_xlabel('Time (seconds)')
ax3.set_yticks([0, 1])
ax3.set_yticklabels(['Low', 'High'])
ax3.grid(True)

# 设置全局参数
plt.suptitle('SPI Signal Timing Diagram')
plt.tight_layout()
plt.show()
